package com.huluobo.a2307douyindemo.utils

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.animation.AccelerateInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import com.huluobo.a2307douyindemo.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.util.Random
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/9/22.
 */
class RedHeartRainView(context: Context, attributeSet: AttributeSet) : RelativeLayout(context, attributeSet) {
    private lateinit var timer: Timer

    fun start() {
        //实例化计时器
        timer = Timer()
        //通过计时器产生内容,每隔100毫秒产生一次
        timer.schedule(timerTask {
            //使用协程的runOnUIThread
            runBlocking(Dispatchers.Main) {
                val iv = ImageView(context)
                iv.setImageResource(R.drawable.ic_xihuanred)
                val params = LayoutParams(100, 100)
                //设置随机的左边距
                val left = Random().nextInt(1080)
                params.topMargin = 0
                params.leftMargin = left
                iv.layoutParams = params

                val animator = ObjectAnimator.ofFloat(iv, "translationY", 0f, 1920f)
                animator.duration = 1000
                animator.interpolator = AccelerateInterpolator()
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        //当下落完成时,移除掉IV
                        removeView(iv)
                    }
                })
                animator.start()

                addView(iv)
            }
        }, 0, 100)
    }
}